using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using backend.Data;
using backend.Models;
using backend.Models.Dtos;
using Microsoft.EntityFrameworkCore;

namespace backend.Repositories
{
    public class MaintenanceManRepo : BaseRepo<CampusFacilityRepairManagementDbContext, MaintenanceMan>
    {
        private readonly IMapper _mapper;
        private readonly CampusFacilityRepairManagementDbContext _context;
        public MaintenanceManRepo(CampusFacilityRepairManagementDbContext context, IMapper mapper) : base(context)
        {
            _mapper = mapper;
            _context = context;
        }

        public async Task<SpecificMaintenanceManReturnDto?> GetMaintenanceManByIdAsync(string mid)
        {
            var maintenanceMan = await DbSet
                .Where(mm => mm.MId == mid)
                .Include(mm => mm.MIdNavigation) // 包含用户信息
                .FirstOrDefaultAsync();

            if (maintenanceMan == null)
            {
                return null; // 维修人员不存在
            }

            var maintenanceManReturnDto = new SpecificMaintenanceManReturnDto
            {
                UId = maintenanceMan.MIdNavigation.UId,
                UName = maintenanceMan.MIdNavigation.UName,
                UContact = maintenanceMan.MIdNavigation.UContact,
                USpecialize = maintenanceMan.PId,
                MAverageResponseTime = maintenanceMan.MAverageResponseTime,
                MAverageQuality = maintenanceMan.MAverageQuality,
                MAverageAttitude = maintenanceMan.MAverageAttitude,
                MHiredate = maintenanceMan.MHiredate,
                MFinishedRequests = maintenanceMan.MFinishedRequests,
                MIsResigned = maintenanceMan.MIsResigned
            };

            return maintenanceManReturnDto;
        }

        public async Task<bool> SaveChangesAsync()
        {
            return await Context.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 添加新的维修人员
        /// </summary>
        /// <param name="newMaintenanceMan">要添加的新维修人员实例</param>
        /// <returns>添加后的维修人员实例</returns>
        public async Task<MaintenanceMan> AddMaintenanceManAsync(MaintenanceManCreateDto newDto)
        {
            if (newDto == null)
            {
                throw new ArgumentNullException(nameof(newDto), "New maintenance man cannot be null.");
            }

            var newMaintenanceMan = _mapper.Map<MaintenanceMan>(newDto);
            // Add the new maintenance man to the database
            var createdMaintenanceMan = await DbSet.AddAsync(newMaintenanceMan);
            // Return the created maintenance man instance
            return createdMaintenanceMan.Entity;
        }

        public async Task<int> GetTotalMMCountAsync()
        {
            return await DbSet.CountAsync();
        }

        /// <summary>
        /// 更新现有的维修人员信息
        /// </summary>
        /// <param name="maintenanceManToUpdate">包含更新信息的维修人员实例</param>
        /// <returns>是否成功更新</returns>
        public async Task<bool> UpdateMaintenanceManAsync(string mid, MaintenanceManUpdateDto maintenanceManToUpdate)
        {
            if (maintenanceManToUpdate == null)
            {
                throw new ArgumentNullException(nameof(maintenanceManToUpdate), "Maintenance man to update cannot be null.");
            }

            // Find the existing maintenance man in the database
            var existingMaintenanceMan = await DbSet.FindAsync(mid);
            Console.WriteLine("------Find");
            if (existingMaintenanceMan == null)
            {
                Console.WriteLine("------NotFound");
                return false; // The maintenance man does not exist
            }
            _mapper.Map(maintenanceManToUpdate, existingMaintenanceMan);

            // Save changes to the database
            await SaveChangesAsync();
            return true;
        }

        public async Task<List<MaintenanceManReturnDto>> GetMaintenanceMenList(string role, int page, int number)
        {
            var maintenanceMen = await DbSet
                .Where(m => m.MIdNavigation.URole == role)
                .OrderBy(m => m.MId)
                .Include(m => m.MIdNavigation)
                .Skip((page - 1) * number) // 跳过前 (pageIndex - 1) * pageSize 条记录
                .Take(number) // 获取接下来的 pageSize 条记录
                .Select(m => new MaintenanceManReturnDto
                {
                    UId = m.MId,
                    UName = m.MIdNavigation.UName,
                    USpecialize = _context.Professions.FirstOrDefault(p => p.PId == m.PId).PName, // 如果Specialize是从数据库中获取，请调整此处逻辑
                    MAverageResponseTime = m.MAverageResponseTime ?? 0,
                    MAverageQuality = m.MAverageQuality ?? 0,
                    MAverageAttitude = m.MAverageAttitude ?? 0
                })
                .ToListAsync();

            return maintenanceMen;
        }

        public async Task<SpecificMaintenanceManReturnDto?> GetMaintenanceMan(string mid)
        {
            var maintenanceMan = await DbSet
                .Include(m => m.MIdNavigation)
                .Select(m => new SpecificMaintenanceManReturnDto
                {
                    UId = m.MId,
                    UName = m.MIdNavigation.UName,
                    USpecialize = _context.Professions.FirstOrDefault(p => p.PId == m.PId).PName, // 如果Specialize是从数据库中获取，请调整此处逻辑
                    MAverageResponseTime = m.MAverageResponseTime ?? 0,
                    MAverageQuality = m.MAverageQuality ?? 0,
                    MAverageAttitude = m.MAverageAttitude ?? 0,
                    MHiredate = m.MHiredate,
                    MFinishedRequests = m.MFinishedRequests,
                    MIsResigned = m.MIsResigned
                })
                .FirstOrDefaultAsync(m => m.UId == mid);

            if (maintenanceMan == null)
            {
                return null;
            }
            return maintenanceMan;
        }
    }
}